﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace DCT.Huiteng.Test.App
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = MD5("aaa");
            Console.WriteLine(s.Length);
            //Console.WriteLine(MD5("aaa", Encoding.Default));
        }

        /// <summary>
        /// MD5加密【WebForm】
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MD5(string str)
        {
            return System.Web.Security.FormsAuthentication
                .HashPasswordForStoringInConfigFile(str, "md5");
        }

        /// <summary>
        /// MD5加密(32位)
        /// </summary>
        /// <param name="str"></param>
        /// <param name="strEncoding"></param>
        /// <returns></returns>
        public static string MD5(string str, System.Text.Encoding strEncoding)
        {
            MD5 md5Provider = new MD5CryptoServiceProvider();
            return ByteArrayToHexString(md5Provider.ComputeHash(strEncoding.GetBytes(str)));
        }

        /// <summary>
        /// 数据流转换为十六进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static string ByteArrayToHexString(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                throw new ArgumentException("bytes [] 参数出错");

            StringBuilder hexString = new StringBuilder(2 * bytes.Length);
            for (int i = 0; i < bytes.Length; i++)
                hexString.AppendFormat("{0:X2}", bytes[i]);

            return hexString.ToString();
        }
    }
}
